<script setup>
import { ref, onMounted } from 'vue'
import Peer from 'peerjs'
const myMsg = ref('')
let peer = null
let localConn = null
let remoteVideo = null
onMounted(() => {
  remoteVideo = document.getElementById('remoteVideo')
})
const replayCall = () => {
  console.log('连接...')
  peer = new Peer()
  peer.on('call', (stream) => {
    console.log('call', stream)
    remoteVideo.srcObject = stream
  })
  peer.on('open', () => {
    // 初始化自身的peer后 连接发送端的peer
    let peerId = localStorage.getItem('peerId')
    localConn = peer.connect(peerId)
    // 连接成功后主动发送一个消息
    localConn.on('open', () => {
      console.log('open')
      localConn.send('你好，我是接收方, 我来了')
    })
  })
  // 建立连接后接受对方发送的数据
  peer.on('connection', (conn) => {
    conn.on('data', (data) => {
      console.log('收到发送方的数据', data)
    })
  })
}
// 主动给对方发送数据
const sendData = () => {
  console.log('发送数据')
  conn.send(myMsg.value)
}
const sendVideo = async () => {
  let peerId = localStorage.getItem('peerId')
  const localMediaStream = await navigator.mediaDevices.getUserMedia({ video: true })
  const mediaConnection = peer.call(peerId, localMediaStream)
  mediaConnection.on('stream', (remoteStream) => {
    console.log(2, remoteStream)
  })
}
</script>
<template>
  <el-button @click="replayCall">接通</el-button>
  <el-input v-model="myMsg" />
  <el-button @click="sendData">发送请求</el-button>
  <el-button @click="sendVideo">发送视频流</el-button>
  <video id="remoteVideo" style="width: 420px; height: 200px" autoplay controls></video>
</template>
